package fantasy;

import java.io.IOException;
import java.io.StringReader;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Pattern;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import static com.google.appengine.api.labs.taskqueue.TaskOptions.Builder.*;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class SaveLeaguesSettingsServlet extends HttpServlet {

    /**
	 * 
	 */
	private static final long serialVersionUID = 5521828338178831115L;
	
	// Get Google's User
    private UserService userService;
    private User user;

    // Initiate Persistence Manager for Yahoo OAuth information
	private PersistenceManager pm;

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
        // Stuff to get baseurl
		Properties props = new Properties();
        props.load(this.getClass().getClassLoader().getResourceAsStream("fantasy.properties"));
        String baseurl = props.getProperty("application.baseurl");

        userService = UserServiceFactory.getUserService();
        user = userService.getCurrentUser();
        pm = PMF.get().getPersistenceManager();

		YahooApiQuery yahoo = new YahooApiQuery();
		
		yahoo.setUser(user.getNickname());
		
		String api_url = "http://fantasysports.yahooapis.com/fantasy/v2/users;use_login=1/games;game_keys=mlb/leagues;out=settings,standings";
		
		String all_league_xml = yahoo.query(api_url);
		
		saveLeagueXml(user.getNickname(), all_league_xml);
		
		try {
			Integer nl = getLeagueNum(all_league_xml, "league");
	        Queue queue = QueueFactory.getDefaultQueue();
			
			log(nl + "\n");
			
			for (int i=0; i < nl; i++) {
		        queue.add(url("/cron/saveleagueworker").param("user", user.getNickname()).param("league", String.valueOf(i)));
		       
				//saveLeague(nl.item(i));
			}
			
		} catch (XPathExpressionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	
	private void saveLeagueXml(final String user_nickname, final String xml_as_string) {
		
		LeagueXml l = new LeagueXml();
		l.setUserkey(user_nickname);
		l.setLeaguexml(xml_as_string);
		
		PersistenceManager pm2 = PMF.get().getPersistenceManager();
		try {
			pm2.makePersistent(l);
		} finally {
			pm2.close();
		}
	}
	
	private Integer getLeagueNum(String xml_as_string, String nodes)
	  throws SAXException, IOException, ParserConfigurationException, XPathExpressionException {
		
		InputSource is = new InputSource(new StringReader(xml_as_string));
		
		Document response = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);

		XPathFactory factory = XPathFactory.newInstance();

		XPath xPath=factory.newXPath();
		
		NodeList n = (NodeList)xPath.evaluate("//"+ nodes , response, XPathConstants.NODESET);
		
		int r = n.getLength();
		
		return r;
	}
	
}
